/* level.c */

#include "level.h"

unsigned int plf_verify_level(char * filename)
{
	unsigned int ret = 0;
	struct plf_header header;
	FILE * levelfile;
	if ((levelfile = fopen(filename, "r")) != NULL)
	{
		if (fread(&header, sizeof(header), 1, levelfile) == 1)
		{
			if ((header.id[0] == 'P') && (header.id[1] == 'L') && (header.id[2] == 'F'))
			{
				ret = 1; /* wohoo, all tests passed ^^ */
				// TODO we should really do more tests
			}
			fclose(levelfile);
		} else
		{
			fclose(levelfile);
		}
	}
	return ret;
}

struct plf_header plf_load_header(char * filename)
{
	struct plf_header ret_header;
	FILE *levelfile;
	if (plf_verify_level(filename) == 0)
	{
		levelfile = fopen(filename, "r");
		fread(&ret_header, sizeof(ret_header), 1, levelfile);
		fclose(levelfile);
	} else
	{
		ret_header.version = 0;
	}
	return ret_header;
}

unsigned char plf_generate_level(void)
{
	unsigned char ret = 0;
	unsigned char counter = 0;
	FILE *file_handle;
	struct plf_file genlevel;
	genlevel.header.id[0] = 'P';
	genlevel.header.id[1] = 'L';
	genlevel.header.id[2] = 'F';
	genlevel.header.version = 1;
	sprintf(genlevel.header.author, "user");
	//if (strlen(getenv("USERNAME") < 20)) sprintf(genlevel.header.author, "%s", getenv("USERNAME"));
	//sprintf(genlevel.header.author, "level", getenv("USERNAME"));
	
	while(counter < LEVEL_LENGTH)
	{
		genlevel.bricks[counter] = 1;
		counter++;
	}
	
	file_handle = fopen("level01.plf", "w");
	if (file_handle != NULL)
	{
		fwrite(&genlevel, sizeof(genlevel), 1, file_handle);
		fclose(file_handle);
		ret = 1;
	} else
	{
		ret = 2;
	}	
	return ret;
}
